import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  Select, 
  InputNumber, 
  Switch, 
  Space, 
  Tag, 
  Popconfirm, 
  message,
  Alert,
  Row,
  Col,
  Typography,
  Badge,
  Tabs
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  BellOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { useCities } from '../hooks/useWeatherQueries';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Text } = Typography;
const { TabPane } = Tabs;

interface AlertRule {
  id: string;
  name: string;
  cityId: string;
  cityName?: string;
  metric: string;
  condition: 'greater' | 'less' | 'equal' | 'between';
  value: number;
  maxValue?: number;
  isActive: boolean;
  notificationChannels: string[];
  description?: string;
  createdAt: string;
  lastTriggered?: string;
}

interface AlertLog {
  id: string;
  ruleId: string;
  ruleName: string;
  cityName: string;
  metric: string;
  currentValue: number;
  threshold: number;
  severity: 'info' | 'warning' | 'error';
  message: string;
  triggeredAt: string;
  acknowledged: boolean;
}

const METRIC_OPTIONS = [
  { value: 'temperature', label: '温度', unit: '°C' },
  { value: 'humidity', label: '湿度', unit: '%' },
  { value: 'pressure', label: '气压', unit: 'hPa' },
  { value: 'windSpeed', label: '风速', unit: 'm/s' },
  { value: 'visibility', label: '能见度', unit: 'km' },
  { value: 'uvIndex', label: '紫外线指数', unit: '' },
];

const CONDITION_OPTIONS = [
  { value: 'greater', label: '大于' },
  { value: 'less', label: '小于' },
  { value: 'equal', label: '等于' },
  { value: 'between', label: '在范围内' },
];

const NOTIFICATION_CHANNELS = [
  { value: 'email', label: '邮件通知' },
  { value: 'sms', label: '短信通知' },
  { value: 'webhook', label: 'Webhook' },
  { value: 'dashboard', label: '仪表盘通知' },
];

const AlertSystem: React.FC = () => {
  const [alertRules, setAlertRules] = useState<AlertRule[]>([]);
  const [alertLogs, setAlertLogs] = useState<AlertLog[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRule, setEditingRule] = useState<AlertRule | null>(null);
  const [form] = Form.useForm();
  const [activeTab, setActiveTab] = useState('rules');

  const { data: cities = [] } = useCities();

  // 模拟数据
  useEffect(() => {
    const mockRules: AlertRule[] = [
      {
        id: '1',
        name: '高温预警',
        cityId: '11111111-1111-1111-1111-111111111111',
        cityName: '武汉',
        metric: 'temperature',
        condition: 'greater',
        value: 35,
        isActive: true,
        notificationChannels: ['email', 'dashboard'],
        description: '温度超过35°C时触发预警',
        createdAt: '2024-01-01T10:00:00Z',
        lastTriggered: '2024-01-15T14:30:00Z'
      },
      {
        id: '2',
        name: '低能见度警告',
        cityId: '22222222-2222-2222-2222-222222222222',
        cityName: '上海',
        metric: 'visibility',
        condition: 'less',
        value: 1,
        isActive: true,
        notificationChannels: ['sms', 'webhook'],
        description: '能见度低于1km时发出警告',
        createdAt: '2024-01-01T10:00:00Z'
      }
    ];

    const mockLogs: AlertLog[] = [
      {
        id: '1',
        ruleId: '1',
        ruleName: '高温预警',
        cityName: '武汉',
        metric: 'temperature',
        currentValue: 36.5,
        threshold: 35,
        severity: 'warning',
        message: '武汉当前温度36.5°C，超过预警阈值35°C',
        triggeredAt: '2024-01-15T14:30:00Z',
        acknowledged: false
      },
      {
        id: '2',
        ruleId: '2',
        ruleName: '低能见度警告',
        cityName: '上海',
        metric: 'visibility',
        currentValue: 0.8,
        threshold: 1,
        severity: 'error',
        message: '上海当前能见度0.8km，低于警告阈值1km',
        triggeredAt: '2024-01-15T12:15:00Z',
        acknowledged: true
      }
    ];

    setAlertRules(mockRules);
    setAlertLogs(mockLogs);
  }, []);

  const handleCreateRule = () => {
    setEditingRule(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEditRule = (rule: AlertRule) => {
    setEditingRule(rule);
    form.setFieldsValue(rule);
    setModalVisible(true);
  };

  const handleDeleteRule = (id: string) => {
    setAlertRules(prev => prev.filter(rule => rule.id !== id));
    message.success('删除预警规则成功');
  };

  const handleToggleRule = (id: string, isActive: boolean) => {
    setAlertRules(prev => 
      prev.map(rule => 
        rule.id === id ? { ...rule, isActive } : rule
      )
    );
    message.success(isActive ? '启用预警规则成功' : '停用预警规则成功');
  };

  const handleSaveRule = async (values: any) => {
    try {
      const cityName = cities.find(c => c.id === values.cityId)?.name;
      
      if (editingRule) {
        // 更新规则
        setAlertRules(prev =>
          prev.map(rule =>
            rule.id === editingRule.id
              ? { ...rule, ...values, cityName }
              : rule
          )
        );
        message.success('更新预警规则成功');
      } else {
        // 创建新规则
        const newRule: AlertRule = {
          ...values,
          id: Date.now().toString(),
          cityName,
          createdAt: new Date().toISOString()
        };
        setAlertRules(prev => [...prev, newRule]);
        message.success('创建预警规则成功');
      }
      
      setModalVisible(false);
      form.resetFields();
    } catch (error) {
      message.error('保存预警规则失败');
    }
  };

  const handleAcknowledgeAlert = (id: string) => {
    setAlertLogs(prev =>
      prev.map(log =>
        log.id === id ? { ...log, acknowledged: true } : log
      )
    );
    message.success('已确认告警');
  };

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'error': return 'red';
      case 'warning': return 'orange';
      case 'info': return 'blue';
      default: return 'default';
    }
  };

  const getSeverityIcon = (severity: string) => {
    switch (severity) {
      case 'error': return <ExclamationCircleOutlined />;
      case 'warning': return <WarningOutlined />;
      case 'info': return <CheckCircleOutlined />;
      default: return <BellOutlined />;
    }
  };

  const rulesColumns = [
    {
      title: '规则名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: AlertRule) => (
        <Space>
          <BellOutlined style={{ color: record.isActive ? '#52c41a' : '#d9d9d9' }} />
          <span>{text}</span>
        </Space>
      )
    },
    {
      title: '城市',
      dataIndex: 'cityName',
      key: 'cityName'
    },
    {
      title: '监控指标',
      dataIndex: 'metric',
      key: 'metric',
      render: (metric: string) => {
        const config = METRIC_OPTIONS.find(m => m.value === metric);
        return `${config?.label}(${config?.unit})`;
      }
    },
    {
      title: '条件',
      key: 'condition',
      render: (record: AlertRule) => {
        const conditionText = CONDITION_OPTIONS.find(c => c.value === record.condition)?.label;
        if (record.condition === 'between') {
          return `${conditionText} ${record.value} - ${record.maxValue}`;
        }
        return `${conditionText} ${record.value}`;
      }
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      render: (isActive: boolean, record: AlertRule) => (
        <Switch
          checked={isActive}
          onChange={(checked) => handleToggleRule(record.id, checked)}
          checkedChildren="启用"
          unCheckedChildren="停用"
        />
      )
    },
    {
      title: '最后触发',
      dataIndex: 'lastTriggered',
      key: 'lastTriggered',
      render: (time: string) => time ? new Date(time).toLocaleString() : '从未触发'
    },
    {
      title: '操作',
      key: 'actions',
      render: (record: AlertRule) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditRule(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除此预警规则吗？"
            onConfirm={() => handleDeleteRule(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  const logsColumns = [
    {
      title: '告警级别',
      dataIndex: 'severity',
      key: 'severity',
      render: (severity: string) => (
        <Tag color={getSeverityColor(severity)} icon={getSeverityIcon(severity)}>
          {severity.toUpperCase()}
        </Tag>
      )
    },
    {
      title: '规则名称',
      dataIndex: 'ruleName',
      key: 'ruleName'
    },
    {
      title: '城市',
      dataIndex: 'cityName',
      key: 'cityName'
    },
    {
      title: '告警消息',
      dataIndex: 'message',
      key: 'message'
    },
    {
      title: '触发时间',
      dataIndex: 'triggeredAt',
      key: 'triggeredAt',
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: '状态',
      dataIndex: 'acknowledged',
      key: 'acknowledged',
      render: (acknowledged: boolean, record: AlertLog) => (
        acknowledged ? (
          <Tag color="green">已确认</Tag>
        ) : (
          <Button
            type="link"
            size="small"
            onClick={() => handleAcknowledgeAlert(record.id)}
          >
            确认告警
          </Button>
        )
      )
    }
  ];

  const unacknowledgedCount = alertLogs.filter(log => !log.acknowledged).length;

  return (
    <div>
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={24}>
          <Alert
            message="告警系统状态"
            description={
              <Space>
                <Text>活跃规则: <Badge count={alertRules.filter(r => r.isActive).length} /></Text>
                <Text>未确认告警: <Badge count={unacknowledgedCount} status={unacknowledgedCount > 0 ? 'error' : 'default'} /></Text>
              </Space>
            }
            type={unacknowledgedCount > 0 ? 'warning' : 'info'}
            showIcon
            style={{ marginBottom: 16 }}
          />
        </Col>
      </Row>

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab={`预警规则 (${alertRules.length})`} key="rules">
          <Card
            title="预警规则管理"
            extra={
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleCreateRule}
              >
                创建规则
              </Button>
            }
          >
            <Table
              columns={rulesColumns}
              dataSource={alertRules}
              rowKey="id"
              pagination={{ pageSize: 10 }}
            />
          </Card>
        </TabPane>

        <TabPane tab={`告警日志 (${unacknowledgedCount})`} key="logs">
          <Card title="告警日志">
            <Table
              columns={logsColumns}
              dataSource={alertLogs}
              rowKey="id"
              pagination={{ pageSize: 10 }}
              rowClassName={(record) => 
                record.acknowledged ? '' : 'alert-row-unacknowledged'
              }
            />
          </Card>
        </TabPane>
      </Tabs>

      <Modal
        title={editingRule ? '编辑预警规则' : '创建预警规则'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        width={600}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveRule}
        >
          <Form.Item
            name="name"
            label="规则名称"
            rules={[{ required: true, message: '请输入规则名称' }]}
          >
            <Input placeholder="输入预警规则名称" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="cityId"
                label="监控城市"
                rules={[{ required: true, message: '请选择监控城市' }]}
              >
                <Select placeholder="选择城市">
                  {cities.map((city: any) => (
                    <Option key={city.id} value={city.id}>
                      {city.name} ({city.country})
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="metric"
                label="监控指标"
                rules={[{ required: true, message: '请选择监控指标' }]}
              >
                <Select placeholder="选择指标">
                  {METRIC_OPTIONS.map(metric => (
                    <Option key={metric.value} value={metric.value}>
                      {metric.label}({metric.unit})
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="condition"
                label="触发条件"
                rules={[{ required: true, message: '请选择触发条件' }]}
              >
                <Select placeholder="选择条件">
                  {CONDITION_OPTIONS.map(condition => (
                    <Option key={condition.value} value={condition.value}>
                      {condition.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="value"
                label="阈值"
                rules={[{ required: true, message: '请输入阈值' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="输入阈值"
                  step={0.1}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, currentValues) =>
                  prevValues.condition !== currentValues.condition
                }
              >
                {({ getFieldValue }) => {
                  return getFieldValue('condition') === 'between' ? (
                    <Form.Item
                      name="maxValue"
                      label="最大值"
                      rules={[{ required: true, message: '请输入最大值' }]}
                    >
                      <InputNumber
                        style={{ width: '100%' }}
                        placeholder="输入最大值"
                        step={0.1}
                      />
                    </Form.Item>
                  ) : null;
                }}
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="notificationChannels"
            label="通知渠道"
            rules={[{ required: true, message: '请选择至少一个通知渠道' }]}
          >
            <Select
              mode="multiple"
              placeholder="选择通知渠道"
              options={NOTIFICATION_CHANNELS}
            />
          </Form.Item>

          <Form.Item name="description" label="描述">
            <TextArea
              rows={3}
              placeholder="输入预警规则描述（可选）"
            />
          </Form.Item>

          <Form.Item name="isActive" label="启用规则" valuePropName="checked">
            <Switch checkedChildren="启用" unCheckedChildren="停用" />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingRule ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      <style>{`
        .alert-row-unacknowledged {
          background-color: #fff2e8;
        }
        .alert-row-unacknowledged:hover {
          background-color: #ffe7d3 !important;
        }
      `}</style>
    </div>
  );
};

export default AlertSystem;